import dlib
import cv2
import numpy as np
# 加载并初始化检测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('data/shape_predictor_68_face_landmarks.dat')
camera = cv2.VideoCapture(0)# 从摄像头中取得视频


if not camera.isOpened():
    print("cannot open camear")
    exit(0)

while True:
    #读取视频图像
    ret, frame = camera.read()
    if not ret:
        break
    # 取灰度
    img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # 检测脸部
    dets = detector(img_gray, 1)
    print("Number of faces detected: {}".format(len(dets)))
    # 查找脸部位置
    for i, face in enumerate(dets):
        # 人脸数rects
        rects = detector(img_gray, 0)
        for i in range(len(rects)):
            landmarks = np.matrix([[p.x, p.y] for p in predictor(frame, rects[i]).parts()])
            for idx, point in enumerate(landmarks):
                # 68点的坐标
                pos = (point[0, 0], point[0, 1])
                #print(idx, pos)

                # 利用cv2.circle给每个特征点画一个圈，共68个
                cv2.circle(frame, pos, 2, color=(0, 255, 0))
                # 利用cv2.putText输出1-68
                #font = cv2.FONT_HERSHEY_SIMPLEX
                #cv2.putText(frame, str(idx + 1), pos, font, 0.8, (0, 0, 255), 1, cv2.LINE_AA)

    cv2.imshow("Camera", frame)
    key = cv2.waitKey(1)
    if key == 27:
        break
cv2.destroyAllWindows()
